import { _decorator, Button, Component, director, EventTarget, instantiate, isCCObject, Label, Node, Prefab, RichText, ScrollView, sys } from 'cc';
import { MessageBoxManager } from './MessageBoxManager';
import { SceneItem } from './SceneItem';
const { ccclass, property } = _decorator;

const userDataKey = 'userData';

const userPosDataKey = 'userPosData';

interface MapItemData {
    name: string,
    type: string,
    color: string,
    resources: string[],
    monsters: string[],
    buildings: [],
    events: [],
    // probability: number,
    rules: any,
    position: { x: number, y: number }
}

interface UserData {
    name: string
    race: string
    startPoint: string
    curMap: string
    position: { x: number, y: number }
}

interface MapData {
    name: string
    tiles: MapItemData[]
}
//处理场景内容
@ccclass('MapScene')
export class MapScene extends Component {

    @property(Prefab)
    itemPrefab: Prefab = null;

    @property(MessageBoxManager)
    messageBoxManager: MessageBoxManager = null;

    @property(Label)
    sceneLabel: Label = null;

    //场景中项目详情界面
    @property(Node)
    itemParticulars: Node = null;

    @property(ScrollView)
    sceneView: ScrollView = null;

    /**@param sceneItems1 怪物 */
    sceneItems1: any[] = [];

    /**@param sceneItems2 资源 */
    sceneItems2: any[] = [];

    /**@param NPC组 */
    sceneItems3: any[] = [];

    /**@param 场景设施 */
    sceneItems4: any[] = [];

    /**@param 场景接口 */
    sceneItems5: any[] = [];

    /**@param 物品 */
    sceneItems6: any[] = [];

    sceneItems7: any[] = [];

    sceneSize: number = 0;

    sceneOfPlayPos: { x: number, y: number } = { x: 0, y: 0 };
    start() {
        this.messageBoxManager.showMessage(0, '欢迎来到这是哪里,我也不知道啊');
        this.sceneOfPlayPos.x=this.loadUserData().position.x;
        this.sceneOfPlayPos.y=this.loadUserData().position.y;
        this.loadToScene();
    }

    update(deltaTime: number) {

    }

    //加载玩家所在地图
    loadUserData() {

        const jsonStr = sys.localStorage.getItem(userDataKey);
        const userData = JSON.parse(jsonStr) as UserData;
        return userData;
    }
    //加载
    loadMapData() {

        const jsonStr = sys.localStorage.getItem(this.loadUserData().startPoint + 'MinimapData');
        const mapData = JSON.parse(jsonStr) as MapData;
        return mapData;
    }

    //加载数据丢到场景上显示出来
    loadToScene() {
        this.sceneView.content.children.forEach(i => i.destroy());
        const mapData = this.loadMapData().tiles;
        const mapWidth = Math.sqrt(mapData.length);
        //找到玩家对应地点的数据
        const tileOfPlay = mapData.find(i => i.position.x === this.sceneOfPlayPos.x && i.position.y === this.sceneOfPlayPos.y);
        
        this.sceneLabel.string = tileOfPlay.name;
        
        const type1='设施';
        const type2='资源';
        const type3='动物';
        if (tileOfPlay.buildings.length !== 0) {
            for (const element of tileOfPlay.buildings) {
                this.instanItem(type1,'[设施]',element,'#2F6386','#00000f');
            }
        }
        if (tileOfPlay.resources.length !== 0) {
            for (const element of tileOfPlay.resources) {
                this.instanItem(type2,'[资源]',element,'#529249','#00000f');
            }
        }
        if (tileOfPlay.monsters.length !== 0) {
            for (const element of tileOfPlay.monsters) {
                this.instanItem(type3,'[动物]',element,'#9E5277','#00000f');
            }

        }
        
        this.generDir(tileOfPlay.position.x,tileOfPlay.position.y,mapWidth,mapData);
    }

    //生成可移动的方向
    generDir(x: number, y: number, mapWidth: number,tiles:MapItemData[]) {
        const type4='出口';
        // 左
        if (x > 0) {
            const movX=x-1;
            const movTarget=tiles.find(i=>i.position.x===movX&&i.position.y===y);
            const prefix="[西行]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',movX,y);
        };
        // 上
        if (y < mapWidth - 1) {
            const movY=y+1;
            const movTarget=tiles.find(i=>i.position.x===x&&i.position.y===movY);
            const prefix="[北上]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',x,movY);
        };
        // 右
        if (x < mapWidth - 1) {
            const movX=x+1;
            const movTarget=tiles.find(i=>i.position.x===movX&&i.position.y===y);
            const prefix="[东进]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',movX,y);
        };
        // 下
        if (y > 0) {
            const movY=y-1;
            const movTarget=tiles.find(i=>i.position.x===x&&i.position.y===movY);
            const prefix="[南下]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',x,movY);
        };
        // 左上
        if (x > 0 && y < mapWidth - 1) {
            const movX=x-1;
            const movY=y+1;
            const movTarget=tiles.find(i=>i.position.x===movX&&i.position.y===movY);
            const prefix="[西北]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',movX,movY);
        };
        // 右下
        if (x < mapWidth - 1 && y > 0) {
            const movX=x+1;
            const movY=y-1;
            const movTarget=tiles.find(i=>i.position.x===movX&&i.position.y===movY);
            const prefix="[东南]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',movX,movY);
        };
        // 左下
        if (x > 0 && y > 0) {
            const movX=x-1;
            const movY=y-1;
            const movTarget=tiles.find(i=>i.position.x===movX&&i.position.y===movY);
            const prefix="[西南]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',movX,movY);
        };
        // 右上
        if (x < mapWidth - 1 && y < mapWidth - 1) {
            const movX=x+1;
            const movY=y+1;
            const movTarget=tiles.find(i=>i.position.x===movX&&i.position.y===movY);
            const prefix="[东北]";
            this.instanItem(type4,prefix,movTarget.name,'#83612E','#00000f',movX,movY);
        };
    }

    instanItem(itemType:string,prefix:string,itemName:string,preCor:string,latCor:string,x:number=0,y:number=0){
        const label=`<color=${preCor}>${prefix}</color><color=${latCor}>${itemName}</color>`;
        const item = instantiate(this.itemPrefab);
        item.name=itemName;
        item.getChildByName('RichText').getComponent(RichText).string = label;
        item.getComponent(SceneItem).itemType=itemType;
        if (itemType==='出口') {
            item.getComponent(SceneItem).positionX=x;
            item.getComponent(SceneItem).positionY=y;
            // 设置物品预制体的点击事件，点击时调用 onDirBut 方法并传递当前物品作为参数
            item.on('click', this.onDirBut.bind(this));
        }
        this.sceneView.content.addChild(item);
    }

    onDirBut(event:Event){
        const node = event.target as unknown as Node;
        //变更玩家位置
        this.sceneOfPlayPos.x=node.getComponent(SceneItem).positionX;
        this.sceneOfPlayPos.y=node.getComponent(SceneItem).positionY;

        this.messageBoxManager.showMessage(0,"你进入了"+node.name);
        this.saveUserData();
        this.loadToScene();
    }

    saveUserData() {
                const userData = {
                    name: this.loadUserData().name,
                    race: this.loadUserData().race,
                    startPoint: this.loadUserData().startPoint,
                    curMap: this.loadUserData().curMap,
                    position:{x:this.sceneOfPlayPos.x,y:this.sceneOfPlayPos.y}
                };
                const jsonStr = JSON.stringify(userData);
                sys.localStorage.setItem(userDataKey, jsonStr);
            }

}


